package com.biblioteca.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.biblioteca.model.entities.Usuario;


@SuppressWarnings("serial")
public class FrameLogin extends JFrame {

	private FramePrincipal fp ;
	private JPanel painel ;
	private JTextField fieldUsuario;
	private JTextField fieldSenha;
	
	private PreparedStatement pst ;
	private ResultSet rs ;
	
	public FrameLogin(FramePrincipal frame) {
		fp = frame ;
		fp.setEnabled(false);
		
		//inicializa�ao do frame
		setSize(800/3,600/3) ;
		setResizable(false);
		//setSize(pai.getLargura()/2,pai.getAltura()/2) ;
		setLocationRelativeTo(fp) ;
		setTitle("Login");
		if (fp.getUsuarioAtual() != null) setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		else setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setAlwaysOnTop(true);	
	
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed (WindowEvent e) {
				enableFp() ; 
			}
		
		});
		
		//inicializa�ao do painel
		painel = new JPanel() ;	
		getContentPane().add(painel) ;
		painel.setLayout(null);
		
		fieldUsuario = new JTextField();
		fieldUsuario.setBounds(10, 36, 226, 20);
		painel.add(fieldUsuario);
		fieldUsuario.setColumns(10);
		
		fieldSenha = new JTextField();
		fieldSenha.setBounds(10, 85, 226, 20);
		painel.add(fieldSenha);
		fieldSenha.setColumns(10);
		
		JLabel labelUsuario = new JLabel("Usu\u00E1rio");
		labelUsuario.setBounds(10, 22, 46, 14);
		painel.add(labelUsuario);
		
		JLabel labelSenha = new JLabel("Senha");
		labelSenha.setBounds(10, 72, 46, 14);
		painel.add(labelSenha);
		
		JButton botaoOk = new JButton("OK");
		botaoOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (logar()) dispose() ;		
			}
		});
		botaoOk.setBounds(145, 127, 89, 23);
		painel.add(botaoOk);
	
		
		setVisible(true);
	}

	public boolean logar() {
		try {
			pst = fp.conn.prepareStatement("SELECT nome,nivel FROM Usuario WHERE nome = ? and senha = ? ");
			pst.setString(1, fieldUsuario.getText().trim());
			pst.setString(2, fieldSenha.getText().trim());
			rs = pst.executeQuery();
			if (rs.next()) {
				fp.setUsuarioAtual( new Usuario(rs.getInt(2),rs.getString(1)) );
				pst.close();
				return true ;
			} else {
				pst.close();
				return false ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	public void enableFp() {
		fp.setEnabled(true) ;
		fp.toFront();
	}
}
